package cn.ztq.test0614.service;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ServiceInfo;
import android.os.Build;
import android.os.IBinder;
import android.os.ParcelUuid;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

import cn.ztq.test0614.R;
import cn.ztq.test0614.receiver.BluetoothReceiver;

public class BluetoothService extends Service {
    private final static String TAG = "BluetoothStateService";
    private BluetoothReceiver bluetoothReceiver;
    private LocalBroadcastManager localBroadcastManager;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @SuppressLint("ForegroundServiceType")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            startForeground(0x66, crateNotification(), ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE);
        } else {
            startForeground(0x66, crateNotification());
        }
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        bluetoothReceiver = new BluetoothReceiver(null);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        localBroadcastManager.registerReceiver(bluetoothReceiver, intentFilter);
//        registerReceiver(bluetoothReceiver,intentFilter);
        startBleScan();
        return START_STICKY;
    }

    private void startBleScan() {
        BluetoothManager bluetoothManager = (BluetoothManager) this.getSystemService(Context.BLUETOOTH_SERVICE);
        BluetoothAdapter adapter = bluetoothManager.getAdapter();

        if (adapter != null && adapter.isEnabled()) {
            BluetoothLeScanner scanner = adapter.getBluetoothLeScanner();


            List<ScanFilter> filters = new ArrayList<>();
            UUID uuid=UUID.fromString("0000110b-0000-1000-8000-00805f9b34fb");
            ParcelUuid parcelUuid=new ParcelUuid(uuid);
            ScanFilter e = new ScanFilter.Builder().setServiceUuid(parcelUuid).build();
            filters.add(e);
            ScanSettings settings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            scanner.startScan(getScanFilter(), settings, new ScanCallback() {
                @Override
                public void onScanResult(int callbackType, ScanResult result) {
                    super.onScanResult(callbackType, result);
                    Log.e("onScanResult", "onScanResult");
                }

                @Override
                public void onBatchScanResults(List<ScanResult> results) {
                    super.onBatchScanResults(results);
                    Log.e("onBatchScanResults", "onBatchScanResults");
                }

                @Override
                public void onScanFailed(int errorCode) {
                    super.onScanFailed(errorCode);
                    Log.e("onScanFailed", "onScanFailed");
                }
            });
        }
    }

    public static ParcelUuid uuid = ParcelUuid.fromString("0000fe2c-0000-1000-8000-00805f9b34fb");

    public List<ScanFilter> getScanFilter() {
        byte[] manufacturerData = new byte[27];
        byte[] manufacturerData2 = new byte[17];
        manufacturerData[0] = 7;
        manufacturerData2[0] = 7;
        byte[] serviceDataMTKBeats = new byte[11];
        serviceDataMTKBeats[0] = 0;
        return Arrays.asList(new ScanFilter.Builder().setManufacturerData(76, manufacturerData, manufacturerData).build(),
                new ScanFilter.Builder().setManufacturerData(76, manufacturerData2, manufacturerData2).build(),
                new ScanFilter.Builder().setServiceData(uuid, serviceDataMTKBeats, serviceDataMTKBeats).build()
        );
    }
    @Override
    public void onDestroy() {
        if (bluetoothReceiver != null) {
            unregisterReceiver(bluetoothReceiver);
        }
        super.onDestroy();
    }

    private Notification crateNotification() {
//        Intent notificationIntent = new Intent(this, MainActivity.class);
//        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, ChannelHelper.channelId)
                .setSmallIcon(R.mipmap.ic_launcher_round)
                .setContentTitle("Bluetooth Monitoring")
                .setContentText("Monitoring Bluetooth state...")
//                .setContentIntent(pendingIntent)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT);
        return builder.build();
    }
}
